<?php

/* doc

className: DBCn

Description: Class za vruzka s bazata danni

Example: nema

*/


define('POSTGRESQL', 1);


class DBCn {
	var $mhCn;
	var $mhRs;
	var $mRs;
	var $mCurrentRecord;
	var $mLimit;
	var $mFetched;
	var $mRecordCount;
	var $mEof;
	var $mErrMsg;
	
	function __construct() {
		$this->mFetched = 0;
		$this->mEof = true;
		// echo "construct"; 
	}

	function __destruct() {
		$this->Close();
	}

	function Open($srv = srv, $db = db, $usr = usr, $pass = pass) {
	//function Open($srv = "skylab.etaligent.net", $db = "ropolubo", $usr = "iusrropotamo", $pass = "db^ropotamo?") {
		// $this->mhCn = pg_connect("host=$srv dbname=$db user=$usr password=$pass") or die('Database ERROR!');
		$this->mhCn = pg_connect("host=$srv dbname=$db user=$usr password=$pass");
		if (!$this->mhCn) {
			trigger_error("Unable to open database connection!", E_USER_NOTICE);
			// exit();
		}
		// pg_query($this->mhCn, "SET DateStyle TO 'SQL,European'");
	}

	function Close() {
		if ($this->mhCn) {
			$this->CloseRs();
			if (@pg_close ($this->mhCn)) $this->mhCn = null;
		}
	}

	function CloseRs() {
		if ($this->mhRs) {
			$this->mRs = null;
			$this->mCurrentRecord = 0;
			if (pg_free_result($this->mhRs)) $this->mhRs = null;
		}
	}

	function MoveFirst() {
		if ($this->mCurrentRecord == 1) {
			return $this->mRs;
		} else if ($this->mCurrentRecord > 1) {
			pg_result_seek($this->mhRs, 0);
			$this->mCurrentRecord = 1;
			$this->mFetched = 0;
		}
		return $this->MoveNext();
	}

	function MoveNext() {
		if ($this->mLimit > 0 && $this->mFetched == $this->mLimit) {
			$this->mEof = true;
			return ($this->mRs = null);
		}
		
		$this->mRs = $this->ParseResultArray(pg_fetch_array($this->mhRs));
		$this->mEof = !$this->mRs;
		if (!$this->mEof) {
			$this->mCurrentRecord++;
			$this->mFetched++;
		}
		return $this->mRs;
	}
	
	// move to zapis 
	// $cnt = 1 - purviqt
	
	function MoveTo($cnt) {
		if ($cnt > 0 && (($cnt - 1) < $this->RecordCount()) ) {
			
			if ( !pg_result_seek($this->mhRs, ($cnt - 1)) ) {
				trigger_error("moveTo non-existent record. Please contact xxx.", E_USER_NOTICE);
				exit();
			}
			
			$this->mRs = $this->ParseResultArray(pg_fetch_array($this->mhRs));
			$this->mEof = !$this->mRs;
			if (!$this->mEof) {
				$this->mFetched = 1;
				$this->mCurrentRecord = $cnt;
			}
			return $this->mRs;
		} else {
			return false;
		}
	}
	
	function ParseResultArray($p) {
		for ($i = 0; $i < pg_num_fields($this->mhRs); $i++) {
			if (pg_field_type($this->mhRs, $i)=='bool') {
				if ($p[$i]) {
					if ($p[$i]=='t') {
						$p[$i] = 'true';
						$p[pg_field_name($this->mhRs, $i)] = 'true';
					} else {
						$p[$i] = 'false';
						$p[pg_field_name($this->mhRs, $i)] = 'false';
					}
				}
			}
		}
		return $p;
	}

	function Execute($sqlstr) {
		//var_dump($sqlstr);
		if (DEBUG_SQL==1) trigger_error("Query: $sqlstr ", E_USER_NOTICE);
		$this->mCurrentRecord = 0;
		$this->mFetched = 0;
		$this->mErrMsg = null;
		
		$this->mhRs = pg_query($this->mhCn, $sqlstr);
		
		if (!$this->mhRs) {
			$this->mErrMsg = pg_last_error() ;
			trigger_error("Error executing the query: $sqlstr \nPlease contact xxx.", E_USER_NOTICE);
			return false;
		}
		
		$this->mRecordCount = @pg_num_rows($this->mhRs);
		$this->mEof = (bool) !$this->mRecordCount;
		$this->MoveFirst();
		return true;
	}
	
	function SetLimit($limit) {
		if ($limit >= 0) {
			$this->mLimit = $limit;
		}
	}

	function Eof() {
		return (bool) $this->mEof;
	}
	
	function RecordCount() {
		return $this->mRecordCount;
	}
	
	function FieldCount() {
		return pg_num_fields($this->mhRs);
	}

	function GetField($a) {
		return pg_fetch_field($this->mhRs, $a);
	}
	
	function GetLastError() {
		return $this->mErrMsg;
	}

}

function Con() {
	global $gCn;
	if (get_class($gCn) != 'DBCn') {
		$gCn = new DBCn;
		$gCn->Open();
		//$options='set enable_hashjoin to no; set enable_sort to no;';
		if (defined("DB_CONNECTION_OPTIONS"))
			pg_query($gCn->mhCn, DB_CONNECTION_OPTIONS);
	}
	return $gCn;
}

/*
####################################################
####################################################

function coalesce_str($str) {
	if (is_null($str) || $str=='') $str='&nbsp';
	return $str;
}

####################################################

function get_dicttables() {
	$dictTables=array();
	global $gCn;
	global $dictTables;
	global $fieldsArray;
	$gCn=Con();	
	foreach ($fieldsArray as  $key => $value) {
		if ($fieldsArray[$key]['type']=='select') {
			$gCn->Execute('select id,name from '.$fieldsArray[$key]['dict_table'].';');
			$gCn->MoveFirst();
			$i=0;
			while (!$gCn->EOF()) {			
				// $dictTables[$fieldsArray[$key]['dict_table']]['id']=$gCn->mRs['id'];	
				$dictTables[$fieldsArray[$key]['dict_table']][$gCn->mRs['id']]['name']=$gCn->mRs['name'];
				$i++;
				$gCn->MoveNext();
			}			
		}	
	}
}

####################################################

function gen_selects($table_name,$selected) {
	$sel='<option value="null">&nbsp</option>';
	global $dictTables;
	foreach($dictTables[$table_name] as  $key => $value) {
		$sel.='<option value='.$key;
		if ($selected && $selected==$key) $sel.=' selected';		
		$sel.=' >'.$dictTables[$table_name][$key]['name'].'</option>';
	}
	return $sel;
}

####################################################

function gen_wheresql () {
	$wheresql='where 1=1 ';	
	foreach ($_SESSION['search_values'] as  $key => $value) {		
			$wheresql.='and '.$key." like '%".$value."%' ";
	}	
	return $wheresql;
}

####################################################

function generate_grid($table_name,$count_for_page,$path_to_file,$search_bar=1) {
	global $Page;
	global $fieldsArray;
	global $dictTables;
	global $gCn;

	get_dicttables();
	// echo $form_params;
	if ($_GET['page'])  $page_num=$_GET['page'];
	else {
		unset($_SESSION['wheresql']);
		$page_num=1;
	 }
	if (!$form_file)  $form_file=$Page['Form']['file']; else $form_file.='.php';
	$lhtml='<div style="vertical-align:top;">Страница:  '.$page_num.' </div>		
		<table  vspace="15" hspace="5" border="4" width="90%" style="vertical-align:top" name="table01"> 
			<form name="search_form" method="post">	
				<tr style="text-align:right">
					<td colspan="100%">
						'.$add_menu.'
						<input type="button" name="New" value="Нов запис" onclick="javascript: window.location.href=\''.$form_file.'?mode=new'.$form_params.' \';return false; "/></input>
						<input type="submit" name="search" value="Search"></input>
						<input type="button" name="clearfilter" value="Clear Filter" onClick="clear_filter()"/>
					</td>	
				</tr>
				<tr id="search_row">';
				
	
	// Searchbar
	if ($_POST) {		
		foreach ($fieldsArray as  $key => $value) {
			if (!is_null($_POST[$key]) && $_POST[$key]!='&nbsp' && $_POST[$key]!='' && $_POST[$key]!='null') {
				// echo $key.'=>'.$_POST[$key].'<br>';
				$_SESSION['search_values'][$key]=$_POST[$key];
			} else unset($_SESSION['search_values'][$key]);
		}		
	}
	$wheresql=gen_wheresql();

	if ($search_bar) {
		foreach ($fieldsArray as  $key => $value) {
			$lhtml.='<td>';
			if ($fieldsArray[$key]['type']=='text') {
				$lhtml.='<input type="text" name="'.$key.'" value="'.$_SESSION['search_values'][$key].'" style="width: 100%;"></input>';
			}
			if ($fieldsArray[$key]['type']=='select') {
				$lhtml.='<select name="'.$key.'" >'.gen_selects($fieldsArray[$key]['dict_table'],$_SESSION['search_values'][$key]).'</select>';
			}
			$lhtml.='</td>';
		}
	}
	$lhtml.='		</tr>
			</form>
			<tr align="center">';
	
	// Имена на колони
	foreach ($fieldsArray as  $key => $value) {
		$lhtml.='<td>'.$fieldsArray[$key]['label'].'</td>';
	}
	
	$lhtml.='</tr>';
	
	
	
	// Попълване на грида
	$offset=(($page_num -1)*$count_for_page);
	if (is_null($offset)) $offset=0;
	$sql='select * from '.$table_name.' '.$wheresql.' order by id offset '.$offset.' limit '.$count_for_page.' ;';			
	$gCn=Con();
	$gCn->Execute($sql);
	$gCn->MoveFirst();	
	while (!$gCn->EOF()) {	
		$lhtml.='<tr align="left">';
		foreach ($fieldsArray as  $key => $value) {
			$lhtml.='<td>';
			if($fieldsArray[$key]['type']=='text')	{
				if (!is_null($fieldsArray[$key]['link'])) 
					$lhtml.= '<a href="'.$fieldsArray[$key]['link'].'?objid='.$gCn->mRs['id'].'">';
				$lhtml.= coalesce_str($gCn->mRs[$key]).'</td>';
				if (!is_null($fieldsArray[$key]['link'])) 
					$lhtml.= '</a>';
			}
			if($fieldsArray[$key]['type']=='select')	{			
				$lhtml.= coalesce_str($dictTables[$fieldsArray[$key]['dict_table']][$gCn->mRs[$key]]['name']);	
			}
			$lhtml.='</td>';
		}
		$lhtml.='</tr>';				
		$gCn->MoveNext();
	}
	
	$lhtml.='</table>';
	
	
	
	// Страницирането
	$gCn->Execute('select count(*) from '.$table_name.' '.$wheresql.';');
	$gCn->MoveFirst();
	
	$page_count=ceil($gCn->mRs['count']/$count_for_page);
	$lhtml.='<div align="rigth" vspace="20">';	
	for ( $i=1;$i<=$page_count;$i++) {
		$lhtml.='<a href="'.$path_to_file.'?page='.$i.'">'.$i.'</a> &nbsp&nbsp&nbsp';
	}	
	$lhtml.='</div><BR>';
	return $lhtml;
}

#########################################################################################################
#########################################################################################################


function generate_form($table_name,$path_to_file) {
	global $Page;
	global $fieldsArray;
	global $dictTables;
	global $gCn;
	global $mode;
	
	get_dicttables();
	
	if ($_GET['objid'])  $objid=$_GET['objid'];
	if ($_GET['mode'])  $mode=$_GET['mode']; else $mode='view';	
	if ($_POST['action'])  perform_action($_POST['action'],$table_name,$_POST['id']);
	
	$lhtml='<table  vspace="15" hspace="5" border="1"  style="vertical-align:top;" name="table02" cellpadding="0" width="30%" >  
			<form name="edit_form" method="post">	
				<input type="hidden" name="action" id="action"/>
				<tr style="text-align:right">
					<td colspan="100%"  style="font-style:normal;">';
						if ($mode=='edit' || $mode=='new') {
							$lhtml.='<input type="button" name="save" value="Save" onClick="form_actions(\'save\')" />						
								<input type="button" name="view_mode" value="VIEW" onclick="javascript: window.location.href=\''.$path_to_file.'?mode=view&objid='.$objid.'\';return false; "/>';									
						} else  $lhtml.='<input type="button" name="edit_mode" value="EDIT" onclick="javascript: window.location.href=\''.$path_to_file.'?mode=edit&objid='.$objid.'\';return false; "/>';
					$lhtml.='	<input type="button" name="delete" value="Delete" onClick="form_actions(\'delete\')" />
							<input type="button" name="close" value="Close" OnClick="location.href=\''.$Page['Grid']['file'].'\';" />
					</td>
				</tr>';
	
	// Попълване на формата
	 if ($mode=='new') {
		foreach ($fieldsArray as  $key => $value) {			
			$lhtml.='<tr><td  align="right">'.$fieldsArray[$key]['label'].' :';
			$lhtml.='<td align="left">';
			$lhtml.='<input type="hidden" name="id" value="'.$gCn->mRs['id'].'"/>';
			
			if (($fieldsArray[$key]['type']=='text'))	{					
					$lhtml.='<input type="text" name="'.$key.'"  size="30%"></input>';
			}
			if($fieldsArray[$key]['type']=='select')	{			
					$lhtml.='<select name="'.$key.'" >'.gen_selects($fieldsArray[$key]['dict_table'],null).'</select>';				
			}
			if ($fieldsArray[$key]['type']=='file') {
						$lhtml.='<input type="file" name="'.$key.'" size="30%"></input>';
			$lhtml.='</td>';
			}
		}
	} else {
		$sql='select * from '.$table_name.' where id='.$objid.' limit 1;';			
		$gCn=Con();
		$gCn->Execute($sql);
		$gCn->MoveFirst();	
		if (!$gCn->EOF()) {			
			foreach ($fieldsArray as  $key => $value) {			
				$lhtml.='<tr><td  align="right">'.$fieldsArray[$key]['label'].' :';
				$lhtml.='<td align="left">';
				$lhtml.='<input type="hidden" name="id" value="'.$gCn->mRs['id'].'"/>';
				
				if($fieldsArray[$key]['type']=='text' || $fieldsArray[$key]['type']=='file' )	{
					if ($mode=='edit') {
						$lhtml.='<input type="text" name="'.$key.'" value="'.$gCn->mRs[$key].'" size="30%"></input>';										
					} else {	$lhtml.=coalesce_str($gCn->mRs[$key]);	
					}
				}
				if($fieldsArray[$key]['type']=='select')	{			
					if ($mode=='edit') {
						$lhtml.='<select name="'.$key.'" >'.gen_selects($fieldsArray[$key]['dict_table'],$gCn->mRs[$key]).'</select>';
					} else {
						$lhtml.= coalesce_str($dictTables[$fieldsArray[$key]['dict_table']][$gCn->mRs[$key]]['name']);						
					}
				}
				$lhtml.='</td>';
			}
		}
	}
	$lhtml.='</td></tr></form></table>';
	
	
		
	return $lhtml;
}


function perform_action($action,$table_name,$objid) {
	global $mode;
	global $gCn;
	global $fieldsArray;
	global $Page;	
	
	
	echo $mode;
	echo $action;
	

	if ($action=='save' && mode=='edit')  {
		$sql='update '.$table_name.' set ';
		foreach ($fieldsArray as  $key => $value) {
			if ($fieldsArray[$key]['type']=='text') {
				if ($_POST[$key]!='') 
					$_POST[$key]="'".$_POST[$key]."'";
				else $_POST[$key]='null';
			}
			
			$sql.=$key.'=';
			// if ($fieldsArray[$key]['type']=='text') 
				$sql.=$_POST[$key].", ";
			// else 	
				// $sql.=$_POST[$key].", ";
		}
		$sql=substr($sql, 0, -2).' where id='.$objid.';';
		// echo $sql;
		$gCn=Con();
		$gCn->Execute($sql);
	}
	
	if ($action=='save' && $mode=='new')  {
		$sql='insert into '.$table_name.' (';
		foreach ($fieldsArray as  $key => $value) {
			$sql.=$key.', ';
		}
		$sql=substr($sql, 0, -2).') values (';
		foreach ($fieldsArray as  $key => $value) {
			if ($fieldsArray[$key]['type']=='text') {
				if ($_POST[$key]!='') 
					$_POST[$key]="'".$_POST[$key]."'";
				else $_POST[$key]='null';
			}
			$sql.=$_POST[$key].", ";
		}
		$sql=substr($sql, 0, -2).');';
		// echo $sql;
		$gCn=Con();
		$gCn->Execute($sql);
	
	
	
	
	}
	$mode='view';
	$action='close';
	
	
	if ($action=='delete')  {
		$sql='delete from '.$table_name.' where id='.$objid.';';	
		// echo $sql;
		$gCn=Con();
		$gCn->Execute($sql);		
		Header ("Location: ".$Page['Grid']['file']);		
		exit;
	}
	
	
	
	if ($action=='close')  {
		Header ("Location: ".$Page['Grid']['file']);		
		exit;
	}
	

}


function generate_Attached_Grids($Attached_Grids) {
	$html='';
	foreach ($Attached_Grids as  $key => $value) {
		// echo '<BR>KUR';
		// generate_grid('contacts',$count_for_page,'/contacts/contacts.php');
		require (getenv("DOCUMENT_ROOT").$Attached_Grids[$key]['path']);
		// var_dump ($Page);
		// include (getenv("DOCUMENT_ROOT").$Page['Grid']['file']);
		$html.=generate_grid($key,9,$Page['Grid']['file']);
		
		// echo 'KUR';
		
	
	}
	
	return $html;

}

/*
function CreateGrid_XML() {
	$dom =  new DOMDocument();
	$dom->load("./Page.xml");
	
	global $fieldsArray;
	global $dictTables;
	global $gCn;

	get_dicttables();
	// echo $form_params;
	
	if ($_GET['page'])  $page_num=$_GET['page'];
	else {
		unset($_SESSION['wheresql']);
		$page_num=1;
	 }
	 
	// if (!$form_file)  $form_file=$Page['Form']['file']; else $form_file.='.php';
	$lhtml='<div style="vertical-align:top;">Страница:  '.$page_num.' </div>		
		<table  vspace="15" hspace="5" border="4" width="90%" style="vertical-align:top" name="table01"> 
			<form name="search_form" method="post">	
				<tr style="text-align:right">
					<td colspan="100%">
						'.$add_menu.'
						<input type="button" name="New" value="Нов запис" onclick="javascript: window.location.href=\''.$form_file.'?mode=new'.$form_params.' \';return false; "/></input>
						<input type="submit" name="search" value="Search"></input>
						<input type="button" name="clearfilter" value="Clear Filter" onClick="clear_filter()"/>
					</td>	
				</tr>
				<tr id="search_row">';
				
	
	// Searchbar
	if ($_POST) {		
		foreach ($fieldsArray as  $key => $value) {
			if (!is_null($_POST[$key]) && $_POST[$key]!='&nbsp' && $_POST[$key]!='' && $_POST[$key]!='null') {
				// echo $key.'=>'.$_POST[$key].'<br>';
				$_SESSION['search_values'][$key]=$_POST[$key];
			} else unset($_SESSION['search_values'][$key]);
		}		
	}
	$wheresql=gen_wheresql();

	if ($search_bar) {
		foreach ($fieldsArray as  $key => $value) {
			$lhtml.='<td>';
			if ($fieldsArray[$key]['type']=='text') {
				$lhtml.='<input type="text" name="'.$key.'" value="'.$_SESSION['search_values'][$key].'" style="width: 100%;"></input>';
			}
			if ($fieldsArray[$key]['type']=='select') {
				$lhtml.='<select name="'.$key.'" >'.gen_selects($fieldsArray[$key]['dict_table'],$_SESSION['search_values'][$key]).'</select>';
			}
			$lhtml.='</td>';
		}
	}
	$lhtml.='		</tr>
			</form>
			<tr align="center">';
	
	// Имена на колони
	foreach ($fieldsArray as  $key => $value) {
		$lhtml.='<td>'.$fieldsArray[$key]['label'].'</td>';
	}
	
	$lhtml.='</tr>';
	
	
	
	// Попълване на грида
	$offset=(($page_num -1)*$count_for_page);
	if (is_null($offset)) $offset=0;
	$sql='select * from '.$table_name.' '.$wheresql.' order by id offset '.$offset.' limit '.$count_for_page.' ;';			
	$gCn=Con();
	$gCn->Execute($sql);
	$gCn->MoveFirst();	
	while (!$gCn->EOF()) {	
		$lhtml.='<tr align="left">';
		foreach ($fieldsArray as  $key => $value) {
			$lhtml.='<td>';
			if($fieldsArray[$key]['type']=='text')	{
				if (!is_null($fieldsArray[$key]['link'])) 
					$lhtml.= '<a href="'.$fieldsArray[$key]['link'].'?objid='.$gCn->mRs['id'].'">';
				$lhtml.= coalesce_str($gCn->mRs[$key]).'</td>';
				if (!is_null($fieldsArray[$key]['link'])) 
					$lhtml.= '</a>';
			}
			if($fieldsArray[$key]['type']=='select')	{			
				$lhtml.= coalesce_str($dictTables[$fieldsArray[$key]['dict_table']][$gCn->mRs[$key]]['name']);	
			}
			$lhtml.='</td>';
		}
		$lhtml.='</tr>';				
		$gCn->MoveNext();
	}
	
	$lhtml.='</table>';
	
	
	
	// Страницирането
	$gCn->Execute('select count(*) from '.$table_name.' '.$wheresql.';');
	$gCn->MoveFirst();
	
	$page_count=ceil($gCn->mRs['count']/$count_for_page);
	$lhtml.='<div align="rigth" vspace="20">';	
	for ( $i=1;$i<=$page_count;$i++) {
		$lhtml.='<a href="'.$path_to_file.'?page='.$i.'">'.$i.'</a> &nbsp&nbsp&nbsp';
	}	
	$lhtml.='</div><BR>';
	return $lhtml;
}
*/






?>